package com.m31skytech.ElasticTimer;

import com.m31skytech.ElasticTimer.service.ElasticTimerRemoteService;
import com.m31skytech.ElasticTimer.service.IElasticTimerRemoteService;
import com.alibaba.dubbo.common.utils.ConfigUtils;
import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ProtocolConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.alibaba.dubbo.config.ServiceConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ElasticTimerServiceProxy implements InitializingBean {
    static final Logger logger=LoggerFactory.getLogger(ElasticTimerServiceProxy.class);
    @Autowired
    ElasticTimerRemoteService elasticTimerRemoteService;

    @Autowired
    ElasticTimerCuratorHandleService elasticTimerCuratorHandleService;

    static final String DUBBO_APP_PROTOCOL_DUBBO="dubbo";
    static final int DUBBO_APP_THREAD=200;
    static final String DUBBO_APP_VERSION="1.0.0";
    private ServiceConfig<IElasticTimerRemoteService> cachedService;


    @Override
    public void afterPropertiesSet() {
        try{
            setUpElasticTimerRemoteUpdateService();
        }catch (Exception e){
            LoggerFactory.getLogger(ElasticTimerServiceProxy.class).error("something go wrong.",e);
        }
    }

    private void setUpElasticTimerRemoteUpdateService(){
        logger.info("export service start.");
        RegistryConfig registry = new RegistryConfig();
        registry.setAddress(elasticTimerCuratorHandleService.getCurrentOriginZookeeper());
        ApplicationConfig application = new ApplicationConfig();
        application.setName(elasticTimerCuratorHandleService.getCurrentAppname());
        ProtocolConfig protocol = new ProtocolConfig();
        protocol.setName(DUBBO_APP_PROTOCOL_DUBBO);
        protocol.setPort(Integer.parseInt(elasticTimerCuratorHandleService.getCurrentDubboPort()));
        protocol.setThreads(DUBBO_APP_THREAD);
        ServiceConfig<IElasticTimerRemoteService> service = new ServiceConfig();
        service.setApplication(application);
        service.setRegistry(registry);
        service.setProtocol(protocol);
        service.setInterface(IElasticTimerRemoteService.class);
        service.setRef(elasticTimerRemoteService);
        service.setVersion(DUBBO_APP_VERSION);
        service.setTimeout(50000);
        service.export();
        cachedService=service;
        logger.info("ElasticTimerRemoteUpdate Service export success.");

    }
}
